import time
from . import ConnPG
import psycopg2
from sanic.log import logger

class SkuTable:

    async def add_sku(self, spu_id, brand_id, unit_id):#添加sku

        #参数检查
        if not all([spu_id, brand_id, unit_id])\
                    or not spu_id.isdecimal()\
                    or not brand_id.isdecimal()\
                    or not unit_id.isdecimal():

            return {
                'status': -1,
                'errorCode': 110100,
                'errorMsg': '请检查参数，接口有三个必传参数,spu_id、brand_id、unit_id要为整数',
                'resultBody': None
            }

        sql = 'INSERT INTO sku(spu_id, brand_id, unit_id) VALUES (%s, %s, %s)'

        try:
            await ConnPG().execute(sql, (spu_id, brand_id, unit_id))
        except psycopg2.errors.ForeignKeyViolation:

            return {

                'status': -1,
                'errorCode': 110101,
                'errorMsg': '当前spu_id或brand_id或unit_id不存在',
                'resultBody': None,
            }
        else:
        
            return {
                'status': 1,
                'errorCode': None,
                'errorMsg': None,
                'resultBody': "SKU添加成功",
            }
    
    async def select_all_sku(self):#查询所有SKU view_sku表中查询 

        sql = 'select * from view_sku_info order by id DESC'

        result = await ConnPG().fetchall(sql)


        return {
            'status': 1,
            'errorCode': None,
            'errorMsg': None,
            'resultBody': result,
        }

    async def del_sku(self, sku_id):#删除sku

        #参数检查

        if not sku_id or not sku_id.isdecimal:

            return {
                'status': -1,
                'errorCode': 300100,
                'errorMsg': 'sku_id不能为空且为整数类型',
                'resultBody': None
            }

        sql = 'DELETE FROM sku WHERE id=%s'

        try:
            await ConnPG().execute(sql, (sku_id,))
        except psycopg2.errors.ForeignKeyViolation as e:

            # print(e)

            return {

                'status': -1,
                'errorCode': 110112,
                'errorMsg': str(e),
                'resultBody': None,
            }
        else:
        
            return {
                'status': 1,
                'errorCode': None,
                'errorMsg': None,
                'resultBody': "sku删除成功",                                     
            }




